Grokking Oracle Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Oracle Easy
Count Number of Pairs With Absolute Difference K (easy)
Solution: Count Number of Pairs With Absolute Difference K
Degree of an Array (easy)
Solution: Degree of an Array
Find Subsequence of Length K With the Largest Sum (easy)
Solution: Find Subsequence of Length K With the Largest Sum
Rectangle Overlap (easy)
Solution: Rectangle Overlap
Remove All Adjacent Duplicates In String (easy)
Solution: Remove All Adjacent Duplicates In String
Island Perimeter (easy)
Solution: Island Perimeter
Climbing Stairs (easy)
Solution: Climbing Stairs
Move Zeroes (easy)
Solution: Move Zeroes
Excel Sheet Column Title (easy)
Solution: Excel Sheet Column Title
Valid Parentheses (Easy)
Solution: Valid Parentheses
Longest Palindromic Substring (medium)
Solution: Longest Palindromic Substring
Single Element in a Sorted Array (medium)
Solution: Single Element in a Sorted Array
Pairs of Songs With Total Durations Divisible by 60 (medium)
Solution: Pairs of Songs With Total Durations Divisible by 60
Search a 2D Matrix II (medium)
Solution: Search a 2D Matrix II
Minimize Maximum of Array (medium)
Solution: Minimize Maximum of Array
Asteroid Collision (medium)
Solution: Asteroid Collision
Combination Sum (medium)
Solution: Combination Sum
Binary Tree Right Side View (medium)
Solution: Binary Tree Right Side View
Sort Colors (medium)
Solution: Sort Colors
Group Anagrams (Medium)
Solution: Group Anagrams
Decode String (Medium)
Solution: Decode String
Number of Islands (medium)
Solution: Number of Islands
Binary Tree Zigzag Level Order Traversal (medium)
Solution: Binary Tree Zigzag Level Order Traversal
Longest Common Subsequence (medium)
Solution: Longest Common Subsequence
Rotting Oranges (medium)
Solution: Rotting Oranges
Meeting Rooms II (medium)
Solution: Meeting Rooms II
Delete Node in a BST (medium)
Solution: Delete Node in a BST
Remove Duplicate Letters (medium)
Solution: Remove Duplicate Letters
Longest Substring Without Repeating Characters (medium)
Solution: Longest Substring Without Repeating Characters (medium)
Search in Rotated Array (medium)
Solution: Search in Rotated Array
Spiral Matrix (medium)
Solution: Spiral Matrix
Container With Most Water (Medium)
Solution: Container With Most Water
3Sum (medium)
Solution: 3Sum
Simplify Path (medium)
Solution: Simplify Path
Next Permutation (medium)
Solution: Next Permutation
Basic Calculator II (medium)
Solution: Basic Calculator II
Merge Intervals (medium)
Solution: Merge Intervals
Restore IP Addresses (medium)
Solution: Restore IP Addresses
Longest Increasing Subsequence (medium)
Solution: Longest Increasing Subsequence
Validate Binary Search Tree (medium)
Solution: Validate Binary Search Tree
Integer to English Words (hard)
Solution: Integer to English Words
Trapping Rain Water (hard)
Solution: Trapping Rain Water
First Missing Positive (hard)
Solution: First Missing Positive
Merge K Sorted Lists (hard)
Solution: Merge K Sorted Lists
Max Points on a Line (hard)
Solution: Max Points on a Line
Sudoku Solver (hard)
Solution: Sudoku Solver
Longest Valid Parentheses (hard)
Solution: Longest Valid Parentheses
Remove Nth Node From End of List (Medium)
Solution: Remove Nth Node From End of List
Median of Two Sorted Arrays (hard)
Solution: Median of Two Sorted Arrays
Constrained Subsequence Sum (hard)
Solution: Constrained Subsequence Sum
Solution: Count Number of Pairs With Absolute Difference K

Problem Statement

Given an array of integers nums and a positive integer k, return the number of pairs (i, j) where i < j and the absolute difference of nums[i] and nums[j] should be equal to k. In other words, |nums[i] - nums[j]| == k.

Examples

  • Example 1:

    • Input: nums = [1, 3, 5, 7], K = 2
    • Expected Output: 3
    • Justification: The pairs with an absolute difference of 2 are (1, 3), (3, 5), and (5, 7).
  • Example 2:

    • Input: nums = [4, 4, 4, 4], K = 1
    • Expected Output: 0
    • Justification: Each pair of the same elements has an absolute difference of 0. So, there are no pairs that have absolute difference 1.
  • Example 3:

    • Input: nums = [1,3,4,5,2], K = 2
    • Expected Output: 3
    • Justification: The pairs that satisfy the condition are (1, 3), (3, 5), and (4, 2).

Solution

To efficiently solve the problem, we can utilize a HashMap. This approach works by storing the occurrences of each number in the hashmap as we iterate through the array. By doing this, we can check in constant time whether there exists a number in the map such that the absolute difference with the current number is K. Specifically, for each number in the array, we check if either number + K or number - K exists in the HashMap.

This method is effective because it reduces the need for nested loops, thereby decreasing the overall time complexity to linear time, , which is a significant improvement over the brute force approach. Additionally, it uses linear space to maintain the HashMap, making it a balanced approach in terms of both time and space efficiency.

Step-by-step Algorithm

  1. Initialize a HashMap to store each number's occurrence in the array.
  2. Initialize a count to 0 to keep track of the number of valid pairs.
  3. Iterate through the array:
    • For each number, check if (number + K) or (number - K) exists in the HashMap. If it does, increment the counter.
    • Update the HashMap with the current number's occurrence.
  4. Return the counter as the total number of valid pairs.

Algorithm Walkthrough

Let's consider the input nums = [1,3,4,5,2] with K = 2.

  • Initial State:

    • Hashmap: {}
    • nums = [1,3,4,5,2], K = 2
  • Step 1: Process nums[0] = 1

    • Calculate nums[i] + k = 1 + 2 = 3
    • Calculate nums[i] - k = 1 - 2 = -1
    • No matches in hashmap, so no pairs yet.
    • Update Hashmap with 1: 1 (number: frequency)
    • Hashmap: {1: 1}
  • Step 2: Process nums[1] = 3

    • Calculate nums[i] + k = 3 + 2 = 5
    • Calculate nums[i] - k = 3 - 2 = 1
    • Match found for 1 in hashmap, increment count by 1.
    • Update Hashmap with 3: 1
    • Hashmap: {1: 1, 3: 1}
    • Count = 1
  • Step 3: Process nums[2] = 4

    • Calculate nums[i] + k = 4 + 2 = 6
    • Calculate nums[i] - k = 4 - 2 = 2
    • No matches in hashmap, so count remains the same.
    • Update Hashmap with 4: 1
    • Hashmap: {1: 1, 3: 1, 4: 1}
  • Step 4: Process nums[3] = 5

    • Calculate nums[i] + k = 5 + 2 = 7
    • Calculate nums[i] - k = 5 - 2 = 3
    • Match found for 3 in hashmap, increment count by 1.
    • Update Hashmap with 5: 1
    • Hashmap: {1: 1, 3: 1, 4: 1, 5: 1}
    • Count = 2
  • Step 5: Process nums[4] = 2

    • Calculate nums[i] + k = 2 + 2 = 4
    • Calculate nums[i] - k = 2 - 2 = 0
    • Match found for 4 in hashmap, increment count by 1.
    • Update Hashmap with 2: 1
    • Hashmap: {1: 1, 3: 1, 4: 1, 5: 1, 2: 1}
    • Count = 3

Final Output

  • The final count of pairs with an absolute difference of K = 2 is 3.
Image

Code

Java

. . . .

Complexity Analysis

  • Time Complexity: , where n is the number of elements in the array. This is because we are iterating through the array exactly once, and for each element, we perform constant-time operations (insertion and lookup) in the HashMap.
  • *Space Complexity: , as we are using a HashMap to store the occurrences of each element in the array, which in the worst case might contain all unique elements, requiring space proportional to the size of the array.
Count Number of Pairs With Absolute Difference K (easy)
Degree of an Array (easy)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-step Algorithm

Algorithm Walkthrough

Final Output

Code

Complexity Analysis